import network,time


class NetModel:


    # def LogInfo(str):
    #     print(str)
    #     pass
    LogInfo =lambda str: print(str)#信息打印函数  可后续调整
    wlanObj= network.WLAN(network.STA_IF)

    def __init__(self) -> None:
        self.initNet()
        pass
    
    def initNet(self):
        NetModel.wlanObj.active(True)
        pass

    def connectWifi(self,wlan=wlanObj,ssid="",password=""):
        NetModel.LogInfo("初始化网络")
        self.initNet()
        NetModel.wlanObj.disconnect()
        NetModel.LogInfo("网络初始化完成")
        NetModel.LogInfo("准备连接wifi")
        #模式区分
        connectModel = 0# 0表示ssid +password 连接 1表示 ssid|list +password尝试连接 2.defConnect
        if ssid == "":
            connectModel = 1
        if password == "":
            connectModel = 2  
        #模式调用
        if int(connectModel) == 0:#正常密码连接模式
            self.connect_model_1(wlan,ssid,password)
        if int(connectModel) == 1:#只知道密码进行扫描连接
            self.connect_model_2(wlan,password)
        if int(connectModel) == 2:#连接开放Wifi
            self.connect_model_3(wlan)
            pass
        return wlan.isconnected()
        
    def connect_model_1(self,wlan,ssid,password):
        maxCount=10#最大尝试重连次数
        wlan.disconnect()
        NetModel.LogInfo(f"连接wifi中...{ssid}")
        while not wlan.isconnected() and maxCount > 0:
            wlan.connect(ssid,password)
            time.sleep(1)
            print(f"Wifi Connect status{wlan.isconnected()}")
            maxCount=maxCount-1
        NetModel.LogInfo(f"WiFi连接{wlan.isconnected()}{wlan.ifconfig()}")
        return wlan.isconnected()    

    def connect_model_2(self,wlan,password):
        # wlan= network.WLAN(network.STA_IF)
        wlan.disconnect()
        for i in range(0,10):#检测十次
            wifiList = wlan.scan()
            for wifi in wifiList:
                NetModel.LogInfo(f"try connect wifi{ wifi.ssid}:{ password}")
                wlan.connect(wifi[0],password)#(b's-night-y', b'ddJ\xa8\x88m', 6, -28, 4, False)
                if wlan.isconnected() :
                    NetModel.LogInfo(f"连接到Wifi{wifi.ssid}:pass{password}")
                    return wlan.isconnected()
                pass
            time.sleep(1)
            
        return wlan.isconnected()

    def connect_model_3(self,wlan):
        # wlan= network.WLAN(network.STA_IF)
        wlan.disconnect()
        for i in range(0,10):#检测十次
            wifiList = wlan.scan()
            for wifi in wifiList:
                NetModel.LogInfo(f"try connect wifi{wifi.ssid}")
                wlan.connect(wifi[0],"")
                if wlan.isconnected() :
                    NetModel.LogInfo(f"连接到Wifi{wifi.ssid}")
                    return wlan.isconnected()
                pass
            time.sleep(1)
        return wlan.isconnected()